<?php
/**
 * Created by PhpStorm
 * User: 龍zero
 * Date: 2022-04-10
 * Time: 16:28
 */

declare(strict_types=1);

namespace App\Aspect;

use App\Annotation\ParamValid;
use App\Exception\FailedException;
use App\Exception\ParameterException;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Hyperf\Validation\Event\ValidatorFactoryResolved;

/**
 * 简单参数验证
 * @Aspect()
 * Class SimpleParamValidAspect
 * @package App\Aspect
 */
class SimpleParamValidAspect extends AbstractAspect
{
    /**
     * @Inject()
     * @var ValidatorFactoryResolved
     */
    private $validatorFactoryResolved;

    public array $annotations = [
        ParamValid::class
    ];

    public function process(ProceedingJoinPoint $proceedingJoinPoint)
    {
        $validMeta = $proceedingJoinPoint->getAnnotationMetadata()->method[ParamValid::class]->toArray();
        if (empty($validMeta['value']) || (is_array($validMeta['value']) && count($validMeta['value']) != count($validMeta['rule']))) {
            throw new FailedException([
                'message' => '注解格式规范错误！'
            ]);
        }
        $rules = [];
        if(is_array($validMeta['value'])){
            foreach ($validMeta['value'] as $key => $value) {
                $rules[$value] = $validMeta['rule'][$key];
            }
        }else{
            $rules[(string)$validMeta['value']] = $validMeta['rule'];
        }
        $requestParams = array_merge($proceedingJoinPoint->arguments['keys'],request()->all());
        $validator = $this->validatorFactoryResolved->validatorFactory->make($requestParams, $rules);
        if ($validator->fails()) {
            throw new ParameterException([
                'message' => $validator->errors()
            ]);
        }
        $res = $proceedingJoinPoint->process();
        return $res;
    }
}